import os
from PIL import Image

def compress_images_in_folder(folder_path, output_folder, quality=50):
    # 确保输出文件夹存在
    os.makedirs(output_folder, exist_ok=True)

    # 遍历文件夹中的文件
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        output_path = os.path.join(output_folder, filename)

        # 检查是否为图片文件
        if os.path.isfile(file_path) and any(file_path.lower().endswith(extension) for extension in ['.jpg', '.jpeg', '.png']):
            # 打开图片
            image = Image.open(file_path)
            # 将图像转换为RGB模式（如果有Alpha通道）
            if image.mode == 'RGBA':
                image = image.convert('RGB')
            # 压缩图片
            image.save(output_path, optimize=True, quality=quality)

            print(f"已压缩图片: {filename}")

# 要压缩的图片所在的文件夹路径
input_folder = '/Users/edmond/Downloads/证件图片'

# 压缩后的图片输出文件夹路径
output_folder = '/Users/edmond/Downloads/证件图片/压缩后'

# 执行图片压缩
compress_images_in_folder(input_folder, output_folder, quality=50)
